package bfa.gps;


import java.util.Timer;
import java.util.TimerTask;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Color;
import android.location.GpsSatellite;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

public class GpsKeepAliveActivity extends Activity  implements OnSeekBarChangeListener{
	 LocalService mService;

	 SpeedometerView pv;

	 TextView tnofix;
	 TextView tfix;

	 SeekBar fakeSpeed;

	 MediaPlayer gear_hrn;
	 MediaPlayer overSpeed;
	 
	 Intent intent=null;
	 
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
        

        
        if (intent==null) {
            intent=new Intent(this, LocalService.class);
        	//ComponentName myServiceName = 
            startService(intent);
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

            //      stopService(new Intent(this, MyService.class));
            
        	tnofix=(TextView) findViewById(R.id.textSatellitesNoFix);
        	tnofix.setText("");
    		tfix=(TextView) findViewById(R.id.textSatellitesFix);
        	tfix.setText("");
            
            
        	fakeSpeed=(SeekBar) findViewById(R.id.seekBarFakeSpeed);
        	fakeSpeed.setOnSeekBarChangeListener(this);
        	
            pv=(SpeedometerView) findViewById(R.id.pieView2);	    
            
            UpdateTimeTask1 u=new UpdateTimeTask1();
            u.handler=new MyHandler2();
            timer.schedule(u, 1000, 50);
            
            
            
            
            gear_hrn = MediaPlayer.create(getApplicationContext(), R.raw.gear_hrn);
            overSpeed= MediaPlayer.create(getApplicationContext(), R.raw.overspeed);
            
//            OnCompletionListener ocl=new OnCompletionListener() {			
//    			@Override
//    			public void onCompletion(MediaPlayer mp) {
//    				if (overSpeedCatch) {	
//    	        		
//    	        	}
//    					
//    			}
//    		};
//    		overSpeed.setOnCompletionListener(ocl);
        	
        }
		

    }
    
    
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            //Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        }
    }
    
    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            @SuppressWarnings("unchecked")
			LocalBinder<LocalService> binder = (LocalBinder<LocalService>) service;
            
            mService = binder.getService();
            mService.setHandler(new MyHandler2());
        	mService.setSomeBodyListening(true);    		
            //mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            //mBound = false;
        }
    };

    
	private class MyHandler2 extends Handler {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			
			Bundle bundle = msg.getData();
			if (bundle.containsKey("gpsProvider")) {
				String value = bundle.getString("gpsProvider");

				ToggleButton t=(ToggleButton) findViewById(R.id.satStatus);
				t.setChecked(value.equals("enabled"));
				t.invalidate();
				Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
				
			}
			if (bundle.containsKey("gpsStatus")) {
				//String value = bundle.getString("gpsStatus");
				//Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
				
				
			}
			if (bundle.containsKey("firstFix")) {
				String value = bundle.getString("firstFix");
				Toast.makeText(getApplicationContext(), "Fix acquired in "+value+" sec.", Toast.LENGTH_SHORT).show();
				
				
			}
			if (bundle.containsKey("satUpdate")) {

				tnofix.setText("");
				tfix.setText("");
				for (GpsSatellite oSat:mService.getSatellites()) {
					if (! oSat.usedInFix()) {
						tnofix.setText(
							tnofix.getText()+"*"
						);						
					} else {
						tfix.setText(
								tfix.getText()+"*"
							);												
					}
				}
				
			}
			
			if (bundle.containsKey("speed")) {
				newSpeed(new Float(bundle.getString("speed")));
			}
			
			
			if (bundle.containsKey("inv")) {
				pv.fromDesiredToIndicated();
			}

			if (bundle.containsKey("checkFix")) {
				if (mService!=null) {
					if (pv.isHasFix()!=mService.hasFix) {
												
						pv.setHasFix(mService.hasFix);
						pv.invalidate();
					}					
				}
			}
			
		}
	}
    
	
    TextView criteriaText;
    
    @Override
    protected void onStart() {    	
    	super.onStart();
    	
		getPrefs();

//    	criteriaText= (TextView)  findViewById(R.id.criteria);        
//        Criteria criteria=new Criteria();       
//        int a=criteria.getAccuracy();        
//        criteriaText.setText( new Integer(a).toString() );
//        criteria.setAccuracy(Criteria.ACCURACY_FINE);
    	

    }
    
    @Override
    public void onStop() {
    	super.onStop();
    }

    @Override
    public void onDestroy() {
    	super.onDestroy();

    	if(isFinishing()){
    		getApplicationContext().unbindService(mConnection);
    	}

    }
    
    @Override    
    public void onBackPressed() {
        moveTaskToBack(true);
    }

    
    public void onQuitButtonClick(View view) {
    	super.onBackPressed();
    }

    public void onResume() {
    	super.onResume();   
    	if (mService!=null) {
        	mService.setSomeBodyListening(true);    		
    	}
    }
    
    public void onPause() {
    	super.onPause();    	
    	if (mService!=null) {
        	mService.setSomeBodyListening(false);    		
    	}
    }
    
    
	Timer timer = new Timer();

	class UpdateTimeTask1 extends TimerTask {
		public Handler handler=null;
		Bundle b = new Bundle();
		Bundle b2 = new Bundle();

	    long lastSecTime=0;
	    
		public void run() {
			 if (handler!=null) {	
			    Message msg = handler.obtainMessage();
			    b.putString("inv","");
			    msg.setData(b);
			    handler.sendMessage(msg);
			    
			    if (System.currentTimeMillis()-lastSecTime>=1000) {
				    Message msg2 = handler.obtainMessage();
				    b2.putString("checkFix","");
				    msg.setData(b2);
				    handler.sendMessage(msg2);
				    lastSecTime=System.currentTimeMillis();
			    }
			 }
		   }
		}
    
	
	float maxDiff =2;
	private void getPrefs() {
		SharedPreferences sharedPreferences = 
			PreferenceManager.getDefaultSharedPreferences(getBaseContext())
		;

		pv.setMaxDiff(sharedPreferences.getFloat("maxDiff",2));

		
		pv.setSmoothMovement(
				sharedPreferences.getBoolean("enableSmoothMovement", true)
		);
		
		enableSound=sharedPreferences.getBoolean("enableSound", false);
		if (! enableSound) {
			if (gear_hrn!=null) {
				if (gear_hrn.isPlaying()) {
					gear_hrn.stop();
				}				
			}
			if (overSpeed!=null) {
				if (overSpeed.isPlaying()) {
					overSpeed.stop();
				}
				
			}
		}
		
		
		
		gear_hrn_on=sharedPreferences.getFloat("gear_hrn_on",130);
		gear_hrn_off=sharedPreferences.getFloat("gear_hrn_off",110);
		
		overSpeed_on=sharedPreferences.getFloat("overSpeed_on",145);
		overSpeed_off=sharedPreferences.getFloat("overSpeed_off",135);

		
		pv.clearAlarmSpeedArc();
		if (enableSound) {
			pv.addAlarmSpeedArc((int) overSpeed_off, (int) overSpeed_on, Color.rgb(0x40, 0x00, 0x00));
			pv.addAlarmSpeedArc((int) gear_hrn_off, (int) gear_hrn_on, Color.rgb(0x90, 0x10, 0x10));
		}		
		
		pv.refreshAll();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
	    
	    if (requestCode==Preferences.PREFERENCES_RESULTCODE && resultCode==Preferences.RESULTCODE_FINISH) {
	    	finish();
	    }    
	}

	
	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		//MenuInflater inflater = getMenuInflater();
		//inflater.inflate(R.menu.main, menu);
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onPrepareOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		//menu.findItem(R.id.connect).setEnabled(fgfs == null);
		//menu.findItem(R.id.disconnect).setEnabled(fgfs != null);
		mostraOpzioni();
		return true;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		final int id = item.getItemId();
		if (id == R.id.connect) {
			//showDialog(DIALOG_CONNECT_ID);
		} else if (id == R.id.disconnect) {
//			try {
//				if (fgfs != null)
//					fgfs.close();
//				fgfs = null;
//			} catch (IOException e) {
//				e.printStackTrace();
//			}
		} else if (id == R.id.help) {
//			showDialog(DIALOG_HELP_ID);
		} else if (id == R.id.menuProps) {

			mostraOpzioni();

		} else if (id == R.id.loadDefaultsButton) {

//			Intent i = new Intent(FlightGear.this, Preferences.class);
//			i.setAction("reset");
//			startActivity(i);

		}
		return super.onOptionsItemSelected(item);
	}

	private void mostraOpzioni() {
		Intent i = new Intent(GpsKeepAliveActivity.this, Preferences.class);
		startActivityForResult(i,Preferences.PREFERENCES_RESULTCODE);
		// Some feedback to the user
		Toast.makeText(GpsKeepAliveActivity.this,
			"Here you can enter your settings.",
			Toast.LENGTH_LONG
		).show();
	}

	@Override
	public void onProgressChanged(
			SeekBar seekBar,
			int progress,
		boolean fromUser
	) {
		newSpeed(new Float(progress));		
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		
		
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		
		
	}
	
	private void newSpeed(float speed) {
		pv.setSpeedToIndicate(speed);
		pv.fromDesiredToIndicated();		
		
		sound(speed);
	}


	boolean enableSound=false;
	
	
	boolean gear_hrn_catch=false;
	float gear_hrn_on=130;
	float gear_hrn_off=110;
	
	
	boolean overSpeedCatch=false;
	float overSpeed_on=140;
	float overSpeed_off=135;
	
	
	

	private void sound(float speed) {
		
		if (enableSound) {
			
			if (speed>gear_hrn_on) {
				if (! gear_hrn_catch) {
					if (! gear_hrn.isPlaying()) {
						gear_hrn.start(); // no need to call prepare(); create() does that for you
					}
					gear_hrn_catch=true;
				}
			} else if (speed<gear_hrn_off) {			
				gear_hrn_catch=false;
			}
			
			if (speed>overSpeed_on) {
				if (! overSpeedCatch) {					
					overSpeed= MediaPlayer.create(getApplicationContext(), R.raw.overspeed);
					overSpeed.setLooping(true);
					overSpeed.start(); // no need to call prepare(); create() does that for you					
				
					overSpeedCatch=true;
				}
			} else if (speed<overSpeed_off) {
				overSpeed.stop();				
				overSpeedCatch=false;
			}

		}		
	}
}